<template>
	<view class="container">
		<unicloud-db ref="udb" v-slot:default="{data, loading, error, options}" :options="options"
			:collection="collectionList" :getone="true" :manual="true">
			<view v-if="error">{{error.message}}</view>
			<view v-else-if="loading">
				<uni-load-more :contentText="loadMore" status="loading"></uni-load-more>
			</view>
			<view v-else-if="data" class="detail">
				<view class="detail-item title-item">
					<text class="title">【{{data.category_id[0].text}}】 {{data.title}}</text>
					<uni-icons :type="liked? 'heart-filled' : 'heart'" size="20"
						@click="like(data.user_id[0]._id,data._id)"></uni-icons>
				</view>
				<view class="detail-item">
					<text class="author">{{data.user_id[0].username}}</text>
				</view>
				<view class="detail-item">
					<text class="tags" v-for="(item,index) in data.mall_category_id">{{item.text}}</text>
				</view>
				<view class="detail-item content">
					<text>{{data.content}}</text>
				</view>

				<view class="detail-item">
					<template v-for="(file, j) in data.images">
						<image v-if="file.fileType == 'image'" :src="file.fileID" style="width: 90vw;height: 90vw;">
						</image>
						<uni-file-picker v-if="file.fileType == 'image'" :value="file" :file-mediatype="file.fileType"
							return-type="object" readonly></uni-file-picker>
						<uni-link v-else :href="file.url" :text="file.url"></uni-link>
					</template>
				</view>
			</view>
		</unicloud-db>
		<view class="btns">
			<button type="primary" @click="handleUpdate">修改</button>
			<button type="warn" class="btn-delete" @click="handleDelete">删除</button>
		</view>
	</view>
</template>

<script>
	// 由schema2code生成，包含校验规则和enum静态数据
	import {
		enumConverter
	} from '../../js_sdk/validator/opendb-news-articles.js';
	import {
		mapState,
		mapMutations
	} from 'vuex';
	const db = uniCloud.database()
	const articleApi = uniCloud.importObject('article')
	const userApi = uniCloud.importObject('user')
	export default {
		data() {
			return {

				queryWhere: '',
				collectionList: [db.collection('opendb-news-articles').field(
						'_id,user_id,category_id,title,content,mall_category_id,images,mode').getTemp(),
					db.collection('opendb-news-categories').field('name as text, _id').getTemp(),
					db.collection('opendb-mall-categories').field('name as text, _id').getTemp(),
					db.collection('uni-id-users').field('username,nickname, _id,article_likes_ids').getTemp()
				],
				loadMore: {
					contentdown: '',
					contentrefresh: '',
					contentnomore: ''
				},
				options: {
					// 将scheme enum 属性静态数据中的value转成text
					...enumConverter
				},
				articleData: null // 用于存储文章详细数据

			}
		},
		onLoad(e) {
			this._id = e.id
			this.getDetail(e.id)
		},
		onReady() {
			if (this._id) {
				this.collectionList = [db.collection('opendb-news-articles').where('_id=="' + this._id + '"').field(
						'_id,user_id,category_id,title,content,mall_category_id,images,mode').getTemp(), db.collection(
						'opendb-news-categories').field('name as text, _id').getTemp(), db.collection(
						'opendb-mall-categories').field('name as text, _id').getTemp(),
					db.collection('uni-id-users').field('username,nickname, _id,article_likes_ids').getTemp()
				]
			}
		},
		computed: {
			liked() {
				if (this.articleData && this.articleData.user_info) {
					return this.articleData.user_info.article_likes_ids.includes(this._id);
				}
				return false;
			},
			...mapState({
				userinfo: state => state.userinfo,
			})
		},
		methods: {
			...mapMutations(['setUserInfo']),
			handleUpdate() {
				// 打开修改页面
				uni.navigateTo({
					url: './edit?id=' + this._id,
					events: {
						// 监听修改页面成功修改数据后, 刷新当前页面数据
						refreshData: () => {
							this.$refs.udb.loadData({
								clear: true
							})
						}
					}
				})
			},
			handleDelete() {
				this.$refs.udb.remove(this._id, {
					success: (res) => {
						// 删除数据成功后跳转到list页面
						uni.navigateTo({
							url: './list'
						})
					}
				})
			},
			async like(userid, articleid) { //注意方法或生命周期需使用async异步方式
				try {
					const res = await articleApi.like_article(userid, articleid) //导入云对象后就可以直接调用该对象的方法了，注意使用异步await
					console.log(res) // 结果是3
					// 更新 user_id 数据
					if (this.articleData) {
						const likesIndex = this.articleData.user_info.article_likes_ids.indexOf(articleid);
						if (likesIndex > -1) {
							this.articleData.user_info.article_likes_ids.splice(likesIndex, 1); // 取消收藏
						} else {
							this.articleData.user_info.article_likes_ids.push(articleid); // 添加收藏
						}
						this.setUserInfo(this.articleData.user_info)
						console.log(this.userinfo)
					}
				} catch (e) {
					console.log(e)
				}
			},
			async getDetail(id) {
				try {
					const articleRes = await db.collection('opendb-news-articles').where({
						_id: id
					}).get();
					if (articleRes.result.data && articleRes.result.data.length > 0) {
						const articleData = articleRes.result.data[0];
						const userRes = await userApi.getUserInfoById(articleData.user_id);
						if (userRes.code == 200 && userRes.data) {
							articleData.user_info = userRes.data; // 将用户信息添加到文章数据中
							this.articleData = articleData; // 更新组件数据
						}
					}
				} catch (e) {
					console.log(e);
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		padding: 10px;

		.detail {
			display: flex;
			flex-direction: column;

			.detail-item {
				text-align: center;
				margin-top: 5px;

				.title {
					text-align: center;
					font-size: 25px;
					font-weight: bold;
				}

				.author {
					font-size: 14px;
					color: cadetblue;
				}

				.tags {
					color: red;
					border: 1px red solid;
					border-radius: 5px;
					padding: 1px 3px;
					margin-left: 5px;
					font-size: 25rpx;
				}
			}

			.content {
				height: 200px;
				display: flex;
				font-size: 25px;
				flex-direction: column;
				justify-content: center;
			}

			.title-item {
				display: flex;
				flex-direction: row;
				justify-content: space-between;
			}
		}
	}

	.btns {
		margin-top: 10px;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		flex-direction: row;
	}

	.btns button {
		flex: 1;
	}

	.btn-delete {
		margin-left: 10px;
	}
</style>